package net.lanelife.casino.caipiao.service;

import java.util.Map;

import javax.persistence.Query;

import net.lanelife.casino.caipiao.entity.User;
import net.lanelife.casino.caipiao.entity.statistics.UserDailyStatistics;
import net.lanelife.casino.caipiao.repository.api.IUserDailyStatisticsRepository;
import net.lanelife.casino.caipiao.service.api.IUserDailyStatisticsService;
import net.lanelife.casino.common.repository.support.GenericRepository;
import net.lanelife.casino.common.service.support.GenericService;

import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserDailyStatisticsService extends GenericService<UserDailyStatistics, Integer> implements IUserDailyStatisticsService {

	@Autowired
	private IUserDailyStatisticsRepository repository;
	
	public UserDailyStatisticsService() {
		super(UserDailyStatistics.class);
	}
	
	@Override
	protected GenericRepository<UserDailyStatistics, Integer> getRepository() {
		return repository;
	}

	/**
	 * 更新用户日结表
	 * @param user
	 * @param reportDate
	 * @param properties
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public int update(User user, LocalDate reportDate, Map<String, Object> properties) throws Exception {
		StringBuilder sql = new StringBuilder("INSERT INTO TB_USER_DAILY_STATISTICS(VERSION,REPORT_DATE,USER_ID,USER_NAME,PARENT_ID,PARENT_NAME,FLOOR,PATH,");
		StringBuilder sql2 = new StringBuilder();
		StringBuilder sql3 = new StringBuilder();
		for (String property : properties.keySet()) {
			sql.append(property).append(",");
			sql2.append(":").append(property).append(",");
			sql3.append(property).append("=").append(property).append("+:").append(property).append(",");
		}
		sql.deleteCharAt(sql.length()-1).append(")VALUES(0,:REPORT_DATE,:USER_ID,:USER_NAME,:PARENT_ID,:PARENT_NAME,:FLOOR,:PATH,");
		sql.append(sql2.deleteCharAt(sql2.length()-1));
		sql.append(") ON DUPLICATE KEY UPDATE VERSION=VERSION+1,");
		sql.append(sql3.deleteCharAt(sql3.length()-1));
		Query query = em.createNativeQuery(sql.toString());
		query.setParameter("REPORT_DATE", reportDate.toDate());
		query.setParameter("USER_ID", user.getId());
		query.setParameter("USER_NAME", user.getUserName());
		query.setParameter("PARENT_ID", user.getParentId());
		query.setParameter("PARENT_NAME", user.getParentName());
		query.setParameter("FLOOR", user.getFloor());
		query.setParameter("PATH", user.getPath());
		for (String property : properties.keySet()) {
			query.setParameter(property, properties.get(property));
		}
		return query.executeUpdate();
	}

	
}
